#include "dac80004.h"
#include "bsp.h"

struct DataFrameDac8000x {
    // first byte
    uint32_t CMD  :4;
    uint32_t RW   :1;
    uint32_t DNC  :3;
    // second byte
    uint32_t DM4  :4;
    uint32_t CH   :4;
    // thrid byte
    uint32_t D8   :8;
    // forth byte
    uint32_t MODE :4;
    uint32_t DL4  :4;
} dac80004Data_t;

uint8_t Dac8000xChToBin[5] = {0x00, 0x01, 0x02, 0x03, 0x0F};

void DrvDac8000x::Init()
{
    BspGpioSet(m_ioLoad, GPIO_CLR);
    BspGpioSet(m_ioClr, GPIO_CLR);
    for (uint8_t ch = DAC8000x_CHA; ch <= DAC8000x_ACH; ch++) {
        SetDacDataBuffer((DAC8000x_CHx)ch, 0);
    }
    BspGpioSet(m_ioClr, GPIO_SET);
    BspGpioSet(m_ioLoad, GPIO_SET);
}

void DrvDac8000x::SetDacDataBuffer(DAC8000x_CHx ch, uint16_t dacData)
{
    if (ch > DAC8000x_ACH) {
        return;
    }
    DataFrameDac8000x frame;
    frame.CH = Dac8000xChToBin[ch];
    frame.DM4 = dacData >> 12;
    frame.D8 = dacData >> 4;
    frame.DL4 = dacData & 0xf;
    // spi transmit
    BspGpioSet(m_ioCs, GPIO_CLR);
    BspDatabusWrite(m_dataBus, (const uint8_t*)&frame, 4);
    BspGpioSet(m_ioCs, GPIO_SET);
}

void DrvDac8000x::LoadVoltage()
{
    // load voltage output
    BspGpioSet(m_ioLoad, GPIO_CLR);
    BspGpioSet(m_ioLoad, GPIO_SET);
}

